<template>
  <div class="app-container form">
    <h3 class="form-tit">{{formInfo.topicName}}</h3>
    <div class="content" v-html="formInfo.content" id="content"></div>
    <el-form ref="form" :model="formData" label-width="180px" :rules="rules"  :label-position="formInfo.labelPosition" :size="formInfo.tsize">
      <el-form-item v-for="(item,index) in formList" :prop="item.vModel" :label="item.label">
        <el-input v-if="item.itemType == 'one-line-text'" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder" :clearable="item.clearable" :style="{width: '100%'}">
        </el-input>
        <el-input v-if="item.itemType == 'lines-text'" type="textarea" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}">
        </el-input>
        <el-input v-if="item.itemType == 'pass-word'" v-model="formData[`${item.vModel}`]" show-password :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}">
        </el-input>
        <el-input-number v-if="item.itemType == 'counter'" v-model="formData[`${item.vModel}`]" show-password :placeholder="item.placeholder"  :clearable="item.clearable"  :style="{width: '100%'}">
        </el-input-number>
        <el-select v-if="item.itemType == 'drop-down'" v-model="formData[`${item.vModel}`]" :placeholder="item.placeholder" @change="selectChange" :clearable="item.clearable" :style="{width: '100%'}">
          <el-option v-for="(self, index) in item.options" :key="index" :label="self.label"
                     :value="self.value" :disabled="item.disabled"></el-option>
        </el-select>
        <el-cascader v-if="item.itemType == 'cascade-selection'" v-model="formData[`${item.vModel}`]" :options="item['options']"
                     :style="{width: '100%'}" :placeholder="item.placeholder"  :clearable="item.clearable"></el-cascader>
        <el-radio-group v-if="item.itemType == 'radio'" v-model="formData[`${item.vModel}`]">
          <el-radio v-for="(one, index) in item.options" :key="index" :label="one.value"
                    :disabled="item.disabled">{{one.label}}</el-radio>
        </el-radio-group>
        <el-checkbox-group v-if="item.itemType == 'multiple-choice'" v-model="formData[`${item.vModel}`]" @change="getBoxGroup($event,item.vModel,item.actmin,item.actmax)">
          <el-checkbox v-for="(self, index) in item['options']" :key="index" :label="self.value"
                       :disabled="item.disabled">{{self.label}}</el-checkbox>
        </el-checkbox-group>
        <el-switch v-if="item.itemType == 'switch'" v-model="formData[`${item.vModel}`]"></el-switch>
<!--        <el-slider v-if="item.itemType == 'slider'" v-model="formData[`${item.vModel}`]" :max='100' :step='1'></el-slider>-->
        <el-time-picker v-if="item.itemType == 'time-picker'" v-model="formData[`${item.vModel}`]" format="HH:mm:ss" value-format="HH:mm:ss"
                        :picker-options='{"selectableRange":"00:00:00-23:59:59"}' :style="{width: '100%'}"
                         :placeholder="item.placeholder"  :clearable="item.clearable"></el-time-picker>
        <el-time-picker v-if="item.itemType == 'range-time-picker'" v-model="formData[`${item.vModel}`]" is-range format="HH:mm:ss" value-format="HH:mm:ss"
                        :style="{width: '100%'}" start-placeholder="开始时间" end-placeholder="结束时间" range-separator="至"
                          :clearable="item.clearable"></el-time-picker>
        <el-date-picker v-if="item.itemType == 'date-picker'" v-model="formData[`${item.vModel}`]" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                        :style="{width: '100%'}" :placeholder="item.placeholder" :clearable="item.clearable"></el-date-picker>
        <el-date-picker v-if="item.itemType == 'range-date-picker'" v-model="formData[`${item.vModel}`]" type="daterange" format="yyyy-MM-dd"
                        value-format="yyyy-MM-dd" :style="{width: '100%'}" start-placeholder="开始日期" end-placeholder="结束日期"
                        range-separator="至"  :clearable="item.clearable"></el-date-picker>
        <el-rate  v-if="item.itemType == 'score'" v-model="formData[`${item.vModel}`]" ></el-rate>
        <el-color-picker v-if="item.itemType == 'color-selection'" v-model="formData[`${item.vModel}`]" size="medium"></el-color-picker>
        <el-upload
          v-if="item.itemType == 'upload'"
          :action="fieldAction"
          list-type="picture-card"
          :file-list="formData[`${item.vModel}`]"
          accept=".jpg,.jpeg,.png,.gif,.JPG,.JPEG,.PBG,.GIF"
          :on-preview="handlePictureCardPreview"
          :on-success="(response, file, fileList)=>{return viewPic(response, file, fileList,item.vModel)}"
          :on-remove="(file, fileList) => { return handleRemove(file,fileList,item.vModel) }">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <div style="text-align: center;">
        <el-button v-if="type!='view'" type="primary" @click="onSubmit">保存</el-button>
        <el-button @click="back">取消</el-button>
      </div>
    </el-form>
    <div class="success" v-if="ifSuccess">
      <i class="el-icon-success" style="font-size:30px;"></i>
      <h3>{{dialogText}}</h3>
    </div>
  </div>
</template>

<script>
import { formDetail,addData } from "@/api/form.js";
import {addType, updateType} from "@/api/system/dict/type";
import { clone } from "@/utils/ruoyi"
export default {
  name: "formview",
  data() {
    return {
      formData:{

      },
      //temp:[],
      fieldAction:process.env.VUE_APP_BASE_API+'/common/upload',
      dialogImageUrl: '',
      dialogVisible: false,
      picFeild:'',
      formInfo:{
        labelPosition:'',
        tsize:'',
        gutter:'',
        topicName:'',
        content:''
      },
      ifSuccess:false,
      detail:{},
      formList:[],
      id:'',
      type:'',
      itemType:'',
      rules: {},
      multiple:[],
      dialogText:'',
      designVa(obj){

        return (rule, value, callback) => {
          if ((!value & value !== 0) || value === '') {
            callback();
            return;
          }
          let reg = obj.reg;
          if (reg.test(value)) {
            callback();
          } else {
            callback(new Error(obj.info));
          }
        };
      },
    };
  },
  mounted() {
    this.id = this.$route.query.id
    this.type = this.$route.query.type
    let expireDate = this.$route.query.expireDate
    let status = this.$route.query.status
    if(status == 0){
      this.ifSuccess = true
      this.dialogText = '调查未发布'
    }else{
      if(expireDate){
        this.ifSuccess = this.$moment(this.$moment(expireDate).format('YYYY-MM-DD')).diff(this.$moment(this.$moment().format('YYYY-MM-DD')),'days') <= 0 ? true:false
        this.dialogText = '调查已过期'
      }
    }
    this.getDetail()
  },
  methods: {
    onSubmit(){
      let temp = []
      this.$refs["form"].validate(valid => {
        if (valid) {
          let temp = []
          Object.keys(this.formData).forEach((key,index)=>{
            temp.push( {[key]: this.formData[key] } )
          })
          let tableValue = JSON.stringify(temp)
          addData({topicId:this.id,tableValue:tableValue} ).then(response => {
            //this.$modal.msgSuccess("添加成功");
            this.dialogText = '问卷提交成功'
            this.ifSuccess = true
            //this.$refs["form"].resetFields()
            this.$refs["form"].clearValidate()
            //this.formData = {}
            //this.getDetail()
          });
        }
      });
    },
    getDetail(){
      formDetail(this.id).then((res)=>{
        let temp
        this.formInfo.labelPosition = res.data.labelPosition
        this.formInfo.tsize = res.data.tsize
        this.formInfo.gutter = res.data.gutter
        this.formInfo.topicName = res.data.topicName
        document.title = res.data.topicName
        this.formInfo.content = res.data.content
        temp = res.data.tableAttributeList
        temp.forEach((item=>{
          if(item.clearable == '1'){
            item.clearable = true
          }else{
            item.clearable = false
          }
          if(item.required == '1'){
            item.required = true
          }else{
            item.required = false
          }
          if(item.disabled == '1'){
            item.disabled = true
          }else{
            item.disabled = false
          }
          if(item.changeTag == '1'){
            item.changeTag = true
          }else{
            item.changeTag = false
          }
          Object.keys(item).forEach((key)=>{
            if( (key == 'style' || key == 'options' || key == 'regList') && item[key] != '' ){
              item[key] = JSON.parse(item[key])
            }

            if( key == 'actmax'){
              if(item.actmax == ''){
                item.actmax = ''
              }else{
                item.actmax = Number(item.actmax)
              }
            }
            if( key == 'actmin'){
              if(item.actmin == ''){
                item.actmin = ''
              }else{
                item.actmin = Number(item.actmin)
              }
            }
            if( key == 'regList' && item.regList && item.regList.length > 0){
              this.$set(this.rules,`${item.vModel}`,[])
              item.regList.forEach(one=>{
                Object.keys(one).forEach(oneKey=>{
                  if(oneKey=='max'){
                    this.rules[`${item.vModel}`].push({'max':one.max,'message':one.message})
                  }
                  if(oneKey=='pattern'){
                    this.rules[item.vModel].push({validator:this.designVa({reg:eval(one.pattern),info:one.message}) })
                  }
                })
              })
            }
            if( key == 'required' && item[key]) {
              this.rules[`${item.vModel}`] = this.rules[`${item.vModel}`]||[]
              this.rules[`${item.vModel}`].push({'required':true,'message':'此项必填'})
            }
          })

        }))
        this.formList = temp.filter((item)=>{
          return item.itemType != 'slider'
        })
        this.formList.forEach(item=>{
          if(item.itemType == 'multiple-choice' || item.itemType == 'upload' ){
            this.$set(this.formData,[item.vModel],new Array())
          }else if(item.itemType == 'score' ){
            this.$set(this.formData,[item.vModel], 0)
          }else if(item.itemType == 'switch'){
            this.$set(this.formData,[item.vModel], false)
          }else{
            this.$set(this.formData,[item.vModel], '')
          }
        })
      })
    },
    //图片处理
    handleRemove(file, fileList,field) {
      fileList.forEach((item)=>{
        this.formData[field].push({'url':item.response.url})
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    viewPic(response, file, fileList,field){
      this.formData[field].push({'url':response.url})
    },
    getBoxGroup(e,str,min,max){
      this.formData[`${str}`] = clone(e)
      let temp = e.length
      if(min != '' && temp < min ){
        this.$message.error(`请至少选择${min}个选项`)
      }
      if(max != '' && temp > max ){
        this.$message.error(`最多选择${max}个选项`)
        this.formData[`${str}`].pop()
      }
    },
    selectChange(e){
    },
    back(){
      this.$refs["form"].resetFields()
      this.$router.go(-1);
    }
  },
  updated() {
    let DomList = document.getElementById("content");
    let imgs = DomList.getElementsByTagName("img");
    let tagP = DomList.getElementsByTagName("p");
    if (imgs.length) {
      for (let i = 0; i < imgs.length; i++) {
        imgs[i].style.width = "100%";
        imgs[i].style.height = "100%";
      }
    }
    if (tagP) {
      for (let i = 0; i < tagP.length; i++) {
        tagP[i].style.textIndent = "26px";
      }
    }
  },
  watch:{
    rules:{
      handler(val){
        return val
      },
      deep:true
    }
  }
};
</script>
<style scoped>
.app-container{
  padding:10px !important
}
.content p{
  text-indent: 26px !important;
}
.form-tit{
  margin: 0 0 20px 0;
  border-bottom: 2px solid #eee;
  text-align: center;
  color: #333;
  font-weight: bold;
  background: #f7f7f7;
  line-height: 40px;
}
.success{
  background:rgba(30,144,255,0.85);
  color:#fff;
  position: fixed;
  top:0;
  left:0;
  right:0;
  bottom:0;
  width:100vw;
  height:100vh;
  display:flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  z-index: 999;
}
.success i{
  margin-top:-50px;
}
.form >>> .el-checkbox-group,
.form >>> .el-radio-group{
  display:flex;
  flex-direction: column;
}
.form >>> .el-radio{
  height: 36px;
  align-items: center;
  display: flex;
}
.content >>> img{
  max-width:100% !important;
  height:auto;
}
</style>
